<?php
declare(strict_types=1);

namespace app\controller\api;

use app\BaseController;
use app\model\{Order, User, MerchantFundFlow};
use app\service\{WechatService, AlipayService};
use think\facade\{Db, Log};
use think\Request;

class NotifyController extends BaseController
{
    /**
     * 微信支付回调
     */
    public function wechatNotify(Request $request, $merchant_id)
    {
        try {
            $wechatService = new WechatService($merchant_id);
            $data = $wechatService->handleNotify();
            
            if ($data['return_code'] === 'SUCCESS' && $data['result_code'] === 'SUCCESS') {
                $order = Order::where('order_no', $data['out_trade_no'])->find();
                if (!$order) {
                    throw new \Exception('订单不存在');
                }
                
                // 处理订单支付
                $this->handleOrderPaid($order, 'wechat', $data['transaction_id'], $data['total_fee'] / 100);
            }
            
            return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        } catch (\Exception $e) {
            Log::error('微信支付回调异常: ' . $e->getMessage());
            return '<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[' . $e->getMessage() . ']]></return_msg></xml>';
        }
    }
    
    /**
     * 支付宝支付回调
     */
    public function alipayNotify(Request $request, $merchant_id)
    {
        try {
            $alipayService = new AlipayService($merchant_id);
            $data = $alipayService->handleNotify($request->post());
            
            if ($data['trade_status'] === 'TRADE_SUCCESS') {
                $order = Order::where('order_no', $data['out_trade_no'])->find();
                if (!$order) {
                    throw new \Exception('订单不存在');
                }
                
                // 处理订单支付
                $this->handleOrderPaid($order, 'alipay', $data['trade_no'], $data['total_amount']);
            }
            
            return 'success';
        } catch (\Exception $e) {
            Log::error('支付宝支付回调异常: ' . $e->getMessage());
            return 'fail';
        }
    }
    
    /**
     * 处理订单支付完成
     */
    protected function handleOrderPaid($order, $payment_method, $transaction_id, $amount)
    {
        Db::startTrans();
        try {
            // 更新订单状态
            $order->save([
                'payment_method' => $payment_method,
                'transaction_id' => $transaction_id,
                'fee_actual' => $amount,
                'pay_status' => 1,
                'pay_time' => date('Y-m-d H:i:s'),
                'order_status' => 1
            ]);
            
            // 记录商家资金流水
            MerchantFundFlow::create([
                'merchant_id' => $order->merchant_id,
                'fund_flow_type' => 3, // 订单支付
                'order_no' => $order->order_no,
                'fund_flow_amount' => $amount,
                'fund_flow_time' => date('Y-m-d H:i:s'),
                'create_time' => date('Y-m-d H:i:s')
            ]);
            
            // 发送支付成功通知
            event('OrderPaid', $order);
            
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw $e;
        }
    }
} 